package com.mxl.threaded;
// 使用锁
public class ProducerConsumerExample {
    private final Object lock = new Object();
    private int sharedResource;
    private boolean dataAvailable;

    public void produce() {
        synchronized (lock) {
            while (dataAvailable) {
                try {
                    lock.wait(); // 等待消费者消费数据
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // 生产数据
            sharedResource++;
            System.out.println("Produced: " + sharedResource);
            dataAvailable = true;
            lock.notify(); // 唤醒消费者线程
        }
    }

    public void consume() {
        synchronized (lock) {
            while (!dataAvailable) {
                try {
                    lock.wait(); // 等待生产者生产数据
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // 消费数据
            System.out.println("Consumed: " + sharedResource);
            dataAvailable = false;
            lock.notify(); // 唤醒生产者线程
        }
    }

    public static void main(String[] args) {
        ProducerConsumerExample example = new ProducerConsumerExample();

        Thread producerThread = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                example.produce();
            }
        });

        Thread consumerThread = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                example.consume();
            }
        });

        producerThread.start();
        consumerThread.start();
    }
}